package com.ll.beautymall.ui.home.allbuy.model;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ll.beautymall.bean.HomeAllBuy;
import com.ll.beautymall.bean.HomeProduct;
import com.ll.beautymall.utils.HttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/10/24.
 */
public class AllBuyBiz {
    public void getAllBuyData(HashMap<String, String> parameters, final OnGetAllBuyLisenter lisenter) {
        HttpUtils.getInstance().getAllBuyData(parameters, new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()) {
                    try {
                        String json = response.body();
                        JSONObject obj = new JSONObject(json);
                        JSONObject data = obj.getJSONObject("data");
                        String products_count = data.getString("products_count");
                        JSONArray products = data.getJSONArray("products");
                        Gson gson = new Gson();
                        List<HomeProduct> homeProducts = gson.fromJson(products.toString(), new TypeToken<List<HomeProduct>>() {
                        }.getType());
                        String source = data.getString("source");
                        int next_cursor = data.getInt("next_cursor");
                        String count_ = data.getString("count");
                        int page_count = data.getInt("page_count");
                        String title = data.getString("title");
                        String subtitle = data.getString("subtitle");
                        HomeAllBuy allBuy = new HomeAllBuy(products_count, homeProducts, source, next_cursor, count_, page_count, title, subtitle);
                        if (allBuy != null) {
                            lisenter.onSucced(allBuy);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                lisenter.onFailed("网络连接较慢，请检查网络...");
            }
        });
    }
}
